package com.bootdo.collector.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.collector.utils.HttpClient;
import com.bootdo.screen.domain.PtclusterloadDO;
import com.bootdo.screen.domain.PtnetworkstatusDO;
import com.bootdo.screen.domain.PtresourceDO;
import com.bootdo.screen.service.PtclusterloadService;
import com.bootdo.screen.service.PtnetworkstatusService;
import com.bootdo.screen.service.PtresourceService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;



public class AmbariCountJob2  implements Job {

    private  static  final  String dfsUsedUri = "http://%s:%d/api/v1/clusters/CNPC/services/HDFS/components/DATANODE?fields=metrics/dfs/datanode/DfsUsed,metrics/dfs/datanode/Capacity&format=null_padding&_=%d";

    private  static final  String memUseduri = "http://%s:%d/api/v1/clusters/CNPC/?fields=metrics/memory/Total._avg[%d,%d,15],metrics/memory/Use._avg[%d,%d,15]&_=%d";

    private  static final String networkuri = "http://%s:%d/api/v1/clusters/CNPC/?fields=metrics/network/In._avg[%d,%d,15],metrics/network/Out._avg[%d,%d,15]&_=%d";

    private static final  String cpuuri = "http://%s:%d/api/v1/clusters/CNPC/?fields=metrics/load/1-min._avg[%d,%d,15],metrics/load/Nodes._avg[%d,%d,15]&_=%d";

    private static final String jvmuri = "http://%s:%d/api/v1/clusters/CNPC/services/HDFS/components/NAMENODE?fields=host_components/metrics/rpc/NumOpenConnections,host_components/metrics/jvm/HeapMemoryMax,host_components/metrics/jvm/HeapMemoryUsed&minimal_response=true&_=%d";

    private  static final  String diskurl = "http://%s:%d/api/v1/clusters/CNPC/services/YARN/components/NODEMANAGER?fields=metrics/disk/write_bps._sum[%d,%d,15],metrics/disk/read_bps._sum[%d,%d,15]&format=null_padding&_=%d";


    @Autowired
    private PtclusterloadService ptclusterloadService;

    @Autowired
    private  PtnetworkstatusService ptnetworkstatusService;

    @Autowired
    private PtresourceService ptresourceService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            Double dfs = getDfsUsed();
            Double mem = getMemUsed();
            Map<String, Object> cpu = getCPU();
            Map<String, Object> jvm = getJvmUsed();
            PtclusterloadDO clusterload = new PtclusterloadDO();
            clusterload.setCpupercentage((Double)cpu.get("1min"));
            Date date = new Date();
            date.setTime((Long)cpu.get("time"));
            clusterload.setDatatime(date);
            clusterload.setHeappercentage((Double) jvm.get("jvm"));
            clusterload.setDfspercentage(dfs);
            clusterload.setMempercentage(mem);
            clusterload.setId(100);
            ptclusterloadService.save(clusterload);


            Map<String, Object> disk = getdisk();
            PtresourceDO resource  = new  PtresourceDO();
            resource.setConnection((int)jvm.get("connections"));
            resource.setNodes((int)cpu.get("nodes"));
            resource.setRead((Double) disk.get("read")/1024/1024);
            resource.setWrite((Double) disk.get("write")/1024/1024);

            date.setTime((Long)disk.get("time"));
            resource.setDatetime(date);
            ptresourceService.save(resource);
        } catch (Exception e) {
           e.printStackTrace();
        }

        Map<String, Object> network = getnewworkUsed();

        PtnetworkstatusDO ptnetworks = new PtnetworkstatusDO();
        ptnetworks.setInnetwork((Double) network.get("in"));
        ptnetworks.setOutnetwork((Double) network.get("out"));
        Date date = new Date();
        date.setTime((Long)network.get("time"));
        ptnetworks.setDatetime(date);
        ptnetworkstatusService.save(ptnetworks);








    }


    public static void main(String[] args) throws InterruptedException {


        System.out.println(getdisk());



    }


    public static  Map<String,Object> getdisk() {

        Map<String,Object> map = new HashMap<>();

        String res = HttpClient.get(HttpClient.urlformat2(diskurl));
        JSONObject mem = JSON.parseObject(res).getJSONObject("metrics").getJSONObject("disk");
        JSONArray jobject = mem.getJSONArray("read_bps._sum");
        JSONArray arr = jobject.getJSONArray(0);
        map.put("read",arr.getDouble(0));
        map.put("time",arr.getLong(1)*1000);

//        System.out.println("====》"+arr.getDouble(0));
//        System.out.println("====》"+arr.getLong(1));
        JSONArray memobj = mem.getJSONArray("write_bps._sum");
        JSONArray arr2 = memobj.getJSONArray(0);
//        System.out.println("====》"+arr2.getDouble(0));
//        System.out.println("====》"+arr2.getLong(1));
        map.put("write",arr2.getDouble(0));


        return  map;
    }

    public  static  Map<String,Object> getJvmUsed() {
        String res = HttpClient.get(HttpClient.urlformat(jvmuri));
        JSONObject jvm = JSON.parseObject(res).getJSONArray("host_components").getJSONObject(1).getJSONObject("metrics").getJSONObject("jvm");
        JSONObject rpc = JSON.parseObject(res).getJSONArray("host_components").getJSONObject(1).getJSONObject("metrics").getJSONObject("rpc");
        Double capacity = jvm.getDouble("HeapMemoryMax");
        Double used = jvm.getDouble("HeapMemoryUsed");
        int openconnections = rpc.getInteger("NumOpenConnections");
        Map<String,Object> map = new HashMap<>();
        map.put("jvm", used/capacity*100);
        map.put("connections",openconnections);
        return map;
    }

    public static Double getDfsUsed() {
        String res = HttpClient.get(HttpClient.urlformat(dfsUsedUri));
        JSONObject datanode = JSON.parseObject(res).getJSONObject("metrics").getJSONObject("dfs").getJSONObject("datanode");
        Double used = datanode.getDouble("DfsUsed");
        Double capacity = datanode.getDouble("Capacity");
        return  used/capacity*100;
    }

    public static Double getMemUsed() {
        String res = HttpClient.get(HttpClient.urlformat2(memUseduri));
        JSONObject mem = JSON.parseObject(res).getJSONObject("metrics").getJSONObject("memory");
        JSONArray jobject = mem.getJSONArray("Total._avg");
        JSONArray arr = jobject.getJSONArray(0);
//        System.out.println("====》"+arr.getDouble(0));
//        System.out.println("====》"+arr.getLong(1));
        JSONArray memobj = mem.getJSONArray("Use._avg");
        JSONArray arr2 = memobj.getJSONArray(0);
//        System.out.println("====》"+arr2.getDouble(0));
//        System.out.println("====》"+arr2.getLong(1));
         return arr2.getDouble(0)/arr.getDouble(0);
    }

    public static Map<String,Object>  getCPU() {
        Map<String,Object> map = new HashMap<>();
        String res = HttpClient.get(HttpClient.urlformat2(cpuuri));
        JSONObject mem = JSON.parseObject(res).getJSONObject("metrics").getJSONObject("load");
        JSONArray jobject = mem.getJSONArray("1-min._avg");
        JSONArray arr = jobject.getJSONArray(0);
//        System.out.println("====》"+arr.getDouble(0));
//        System.out.println("====》"+arr.getLong(1));
        JSONArray memobj = mem.getJSONArray("Nodes._avg");
        JSONArray arr2 = memobj.getJSONArray(0);
//        System.out.println("====》"+arr2.getDouble(0));
//        System.out.println("====》"+arr2.getLong(1));
        map.put("time",arr.getLong(1)*1000);
        map.put("1min",arr.getDouble(0));
        map.put("nodes",arr2.getInteger(0));
        return map;
    }

    public static Map<String,Object> getnewworkUsed() {

        Map<String,Object> map = new HashMap<>();

        String res = HttpClient.get(HttpClient.urlformat2(networkuri));
        JSONObject mem = JSON.parseObject(res).getJSONObject("metrics").getJSONObject("network");
        JSONArray jobject = mem.getJSONArray("In._avg");
        JSONArray arr = jobject.getJSONArray(0);
        map.put("in",arr.getDouble(0)/1024);
        map.put("time",arr.getLong(1)*1000);

//        System.out.println("====》"+arr.getDouble(0));
//        System.out.println("====》"+arr.getLong(1));
        JSONArray memobj = mem.getJSONArray("Out._avg");
        JSONArray arr2 = memobj.getJSONArray(0);
//        System.out.println("====》"+arr2.getDouble(0));
//        System.out.println("====》"+arr2.getLong(1));
        map.put("out",arr2.getDouble(0)/1023);



        return  map;

    }
}
